package comm

import (
	"errors"
	"fmt"
	"strings"

	"gitee.com/gitee-go/core"
	"gitee.com/gitee-go/core/bean/httpBean"
	"gitee.com/gitee-go/core/runtime"
	"gopkg.in/yaml.v2"
)

var plugCmds = make(map[string]*plugInfo)

type plugInfo struct {
	e    *runtime.PluginV0
	name string
	ver  string
	ymls *[]byte
}

// 把插件引入内存,方便查找
func PushYmlPlug(m interface{}) (*runtime.PluginV0, error) {
	var bts []byte
	switch m.(type) {
	case string:
		bts = []byte(m.(string))
	case *string:
		bts = []byte(*m.(*string))
	case []byte:
		bts = m.([]byte)
	default:
		return nil, errors.New("type err")
	}
	//conts:=strings.ReplaceAll(*ymls,"{{name}}",m.name)
	//conts=strings.ReplaceAll(conts,"{{version}}",m.ver)
	//commands := make(map[string][]interface{})
	e := &runtime.PluginV0{}
	err := yaml.Unmarshal(bts, e)
	if err != nil {
		return nil, err
	}
	if e.Commands == nil || len(e.Commands) <= 0 {
		return nil, errors.New("commands is err")
	}
	cmds, err := yaml.Marshal(e.Commands)
	if err != nil {
		return nil, fmt.Errorf("commands is err:%v", err)
	}
	var nms []string
	nms = append(nms, e.Name)
	nms = append(nms, e.Alias...)
	for _, nm := range nms {
		if nm == "" {
			continue
		}
		for _, vs := range e.Versions {
			if vs == "" {
				continue
			}

			plugCmds[fmt.Sprintf("%s@%s", nm, vs)] = &plugInfo{
				e:    e,
				name: e.Name,
				ver:  vs,
				ymls: &cmds,
			}
		}
	}
	return e, err
}
func FindPlug(nms string) ([]interface{}, bool) {
	if nms == "" {
		return nil, false
	}
	v, ok := plugCmds[nms]
	if !ok || v.ymls == nil {
		return nil, false
	}
	conts := strings.ReplaceAll(string(*v.ymls), "{{name}}", v.name)
	conts = strings.ReplaceAll(conts, "{{version}}", v.ver)
	commands := make([]interface{}, 0)
	err := yaml.Unmarshal([]byte(conts), &commands)
	if err != nil {
		core.Log.Errorf("FindPlug parseCmds %v", err)
		return nil, false
	}
	return commands, true
}
func PlugNms() []*httpBean.PlugShow {
	ls := make([]*httpBean.PlugShow, 0)
	for k, v := range plugCmds {
		ls = append(ls, &httpBean.PlugShow{
			Key:         k,
			Name:        v.name,
			Author:      v.e.Author,
			Description: v.e.Description,
			Alias:       v.e.Alias,
		})
	}
	return ls
}
